﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.SQLite;
using System.Globalization;
using System.IO;
using System.Linq;
using MediaScraper.Adapters.Plex.Entities;
using MediaScraper.Common;
using Microsoft.Win32;

namespace MediaScraper.Adapters.Plex
{
    public class PlexAdapter : IMediaServerAdapter
    {
        private const string MovieScannerName = "Movie";
        private const string SeriesScannerName = "Series";
        private string _connectionString;
        public string ConnectionString
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_connectionString))
                {
                    _connectionString = GetConnectionString();
                }
                return _connectionString;
            }
        }

        public PlexAdapter()
        {
         
        }


        public string GetSubtitleFileName(VideoInfo videoInfo, CultureInfo culture)
        {
            var result = string.Format("{0}.{1}", videoInfo.FileProcessInfo.FileName,
                                       culture.TwoLetterISOLanguageName);
            return result;
        }

        public VideoInfo ProcessVideoInfo(VideoInfo videoInfo)
        {
            if (videoInfo is SeriesInfo)
            {
                //Pattern:
                //SERIESNAME
                //  Season SEASON
                //      SERIESNAME - sSEASONeEPISODE - EPISODENAME
                var episode = videoInfo as SeriesInfo;
                episode.FileProcessInfo.FileName = string.Format("{0} - s{1}e{2} - {3}", episode.SeriesName, episode.Season.ToString("00"), episode.Episode.ToString("00"), episode.Name);
                episode.FileProcessInfo.ParentFolder = episode.SeriesName;
                episode.FileProcessInfo.FolderName = string.Format("Season {0}", episode.Season);
                return episode;
            }

            //Pattern:
            // NAME (YEAR)
            //  NAME (YEAR)    
            videoInfo.FileProcessInfo.FileName = string.Format("{0} ({1})", videoInfo.Name, videoInfo.Year);
            videoInfo.FileProcessInfo.ParentFolder = string.Empty;
            videoInfo.FileProcessInfo.FolderName = string.Format("{0} ({1})", videoInfo.Name, videoInfo.Year); 

            return videoInfo;
        }

        public IList<string> GetSeriesRootFolders()
        {
            return GetLocationsByScanner(SeriesScannerName);
        }

        public IList<string> GetMoviesRootFolder()
        {
            return GetLocationsByScanner(MovieScannerName);
        }

        private IList<string> GetLocationsByScanner(string scanner)
        {
            var result = new List<string>();
            try
            {
                using (var ctx = new PlexContext(ConnectionString))
                {
                    var tmp = ctx.LibrarySectionsReadOnly.ToList();
                    var selectResult = from s in ctx.LibrarySectionsReadOnly
                                       where s.Scanner.Contains(scanner)
                                       select s.Locations.Select(x => x.RootPath);

                    foreach (var s in selectResult)
                    {
                        result.AddRange(s);
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter.LogError(LoggingCategories.Adapters,"Error loading folders for media type " + scanner,ex);
            }
            return result;
        }
        
        private string GetConnectionString()
        {
            var plexDbpath = GetPlexDatabasePath();
            if (!string.IsNullOrWhiteSpace(plexDbpath))
            {
                var providerConnectionStringBuilder = new SQLiteConnectionStringBuilder()
                    {
                        DataSource = plexDbpath
                    };

                return providerConnectionStringBuilder.ConnectionString;
            }
            return string.Empty;
        }


        private string GetPlexDatabasePath()
        {
            try
            {
                //Get from registry
                var value = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Plex, Inc.\Plex Media Server", "LocalAppDataPath", null);
                var folder = value + @"\Plex Media Server\Plug-in Support\Databases\"; //ToDo: Check path in registry
                var p = Path.Combine(folder, "com.plexapp.plugins.library.db");
                if (File.Exists(p))
                {
                    return p.Replace("\"", string.Empty);
                }
                
                //search in current user folder    
                var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                folder = appData + @"\Plex Media Server\Plug-in Support\Databases\";
                p = Path.Combine(folder, "com.plexapp.plugins.library.db");
                if (File.Exists(p))
                {
                    return p.Replace("\"", string.Empty);
                }
            }
            catch (Exception ex)
            {
                LogWriter.LogError(LoggingCategories.Adapters, "Error locating Plex DB folder",ex);
            }
            LogWriter.LogError(LoggingCategories.Adapters, "Could not find Plex DB");
            return string.Empty;
        }


    }

    public class PlexContext : DbContext
    {
        public PlexContext(string connectionString) : base(new SQLiteConnection(connectionString),true)
        {
            
        }

        public override int SaveChanges()
        {
            throw new InvalidOperationException("This context is read-only.");
        }

        public DbQuery<LibrarySection> LibrarySectionsReadOnly
        {
            get
            {
                return Set<LibrarySection>().AsNoTracking();
            }
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Need this since there is no DbSet<LibrarySection> property
            modelBuilder.Entity<LibrarySection>();
        }

    }
}
